package ${packageStr};

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.*;
import org.springframework.beans.BeanUtils;

<#if "${entity.isAuthorityURL}" =="1">
import org.springframework.security.access.prepost.PreAuthorize;
</#if>

import java.util.List;
import java.util.Date;

import com.ruoyi.domain.OrderEntity;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;


import com.ruoyi.common.utils.poi.ExcelUtil;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import org.springframework.validation.BindingResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import com.ruoyi.common.core.controller.BaseController;


<#if constant??>
import ${constant};
</#if>
import ${servicePath};
import ${voPath};
import ${addDtoPath};
import ${updateDtoPath};
<#if updateStatusDTOPath??>
    <#if "${statucFlag}" =="1">
        import  ${updateStatusDTOPath};
    </#if>
</#if>
import ${queryDtoPath};
import ${entityPath};

@RestController
@Api(tags="${entity.tableComment}")
@RequestMapping("${url}")
public class ${controllerName} extends BaseController{
    @Autowired
    private ${serviceName} ${serviceNm};

    @ApiOperation("分页查询")
    <#if "${entity.isAuthorityURL}" =="1">
    @PreAuthorize("@ss.hasPermi('${entity.authorityURL}:list:limit:page:limit')")
    </#if>
    @PostMapping(value="/list/limit/{page}/{pageLimit}")
    public IPage<${voName}> listLimit(@ModelAttribute ${queryDTO} request, @ModelAttribute OrderEntity orderEntity,@PathVariable Integer page,@PathVariable Integer pageLimit,org.springframework.ui.Model model) {
        ${entityName} entity = convert(request);
        IPage<${entityName}> response = ${serviceNm}.pageList(new Page<${entityName}>(page,pageLimit),entity,orderEntity);

        return convert(response);
    }

    @ApiOperation("根据ID查询详情")
    @GetMapping(value ="/view/{${idFiled}}")
    public ${resultClass }<${voName}> view( @PathVariable("${idFiled}") ${idType} ${idFiled},org.springframework.ui.Model model) {
        ${entityName} source = ${serviceNm}.getById(${idFiled});

        return  ${resultClass }.${successMethod}(convert(source));
    }
/*
    @PostMapping(value = "/list/select")
    @ApiOperation("（页面选择）")
    public ${resultClass }<List<${voName}>> listSelect( ${queryDTO} request) {
    ${entityName} entity = convert(request);
        List<${entityName}> selectList = ${serviceNm}.listOfSelect(entity);
        return  ${resultClass }.${successMethod}(convert(selectList));
    }
*/
/*
    @PostMapping(value = "/display")
    @ApiOperation("（页面显示）")
    public ${resultClass }<${voName}> display(@RequestBody ${queryDTO} request) {
        ${entityName} entity = convert(request);
        List<${entityName}> selectList = ${serviceNm}.listOfSelect(entity);
        return  ${resultClass }.${successMethod}(convert(selectList));
    }*/

    <#if "${entity.isAuthorityURL}" =="1">
        @PreAuthorize("@ss.hasPermi('${entity.authorityURL}:export')")
    </#if>
    @ApiOperation("导出")
    @PostMapping("/export")
    @com.ruoyi.common.annotation.Log(title = "${entity.tableComment}", businessType = com.ruoyi.common.enums.BusinessType.EXPORT)
    public void export(HttpServletResponse response, @RequestBody ${queryDTO} request){
        ${entityName} entity = convert(request);
        List<${entityName}> list = ${serviceNm}.list(entity);
        ExcelUtil<${entityName}> util = new ExcelUtil<${entityName}>(${entityName}.class);
                util.exportExcel(response, list, "${entityName}");
    }

    @ApiOperation("添加")
    <#if "${entity.isAuthorityURL}" =="1">
        @PreAuthorize("@ss.hasPermi('${entity.authorityURL}:add')")
    </#if>
    @PostMapping(value="/add")
    @com.ruoyi.common.annotation.Log(title = "${entity.tableComment}", businessType = com.ruoyi.common.enums.BusinessType.INSERT)
    public ${resultClass }<Boolean> add(@Valid @ModelAttribute ${addDTO} request, BindingResult bindingResult) {
        if(bindingResult.hasErrors()){
             return ${resultClass }.${errorMethod}(bindingResult.getFieldError().getDefaultMessage());
        }
        ${entityName} entity = convert(request);
        entity.setCreateBy(getUserIdStr());
        entity.setCreateTime(new Date());
        int count = ${serviceNm}.insertSelective(entity);
        return count > 0?${resultClass }.${successMethod}(Boolean.TRUE):${resultClass }.${errorMethod}("添加数据失败，请稍后再试");
    }
    @ApiOperation("修改")
    <#if "${entity.isAuthorityURL}" =="1">
        @PreAuthorize("@ss.hasPermi('${entity.authorityURL}:update')")
    </#if>
    @PostMapping(value="/update")
    @com.ruoyi.common.annotation.Log(title = "${entity.tableComment}", businessType = com.ruoyi.common.enums.BusinessType.UPDATE)
    public ${resultClass }<Boolean> update(@Valid @ModelAttribute ${updateDTO} request, BindingResult bindingResult) {
        if(bindingResult.hasErrors()){
              return ${resultClass }.${errorMethod}(bindingResult.getFieldError().getDefaultMessage());
        }
         ${entityName} entity = convert(request);
         entity.setUpdateBy(getUserIdStr());
         entity.setUpdateTime(new Date());
         boolean flag =  ${serviceNm}.updateByPrimaryKey(entity);
         return flag ? ${resultClass }.${successMethod}(Boolean.TRUE):${resultClass }.${errorMethod}("修改数据失败，请稍后再试");
    }

    <#if "${statucFlag}" =="1">
        @ApiOperation("修改状态")
        <#if "${entity.isAuthorityURL}" =="1">
            @PreAuthorize("@ss.hasPermi('${entity.authorityURL}:update:status')")
        </#if>
        @PostMapping(value="/update/status")
        @com.ruoyi.common.annotation.Log(title = "${entity.tableComment}-修改状态", businessType = com.ruoyi.common.enums.BusinessType.UPDATE)
        public ${resultClass}<Boolean> updateState(@ModelAttribute ${updateStatusDTO} request) {
            ${entityName} entity = convert(request);
            boolean flag =  ${serviceNm}.updateByPrimaryKey(entity);
            return flag ? ${resultClass }.${successMethod}(Boolean.TRUE):${resultClass }.${errorMethod}("修改数据失败，请稍后再试");
        }
    <#else>
        <#if "${entity.isAuthorityURL}" =="1">
            @PreAuthorize("@ss.hasPermi('${entity.authorityURL}:del')")
        </#if>
        @ApiOperation("删除数据")
        @GetMapping(value="/del/{${idFiled}}")
        @com.ruoyi.common.annotation.Log(title = "${entity.tableComment}", businessType = com.ruoyi.common.enums.BusinessType.DELETE)
       public ${resultClass}<Boolean> delById(@PathVariable("${idFiled}") ${idType} ${idFiled}) {
            boolean flag =  ${serviceNm}.deleteById(${idFiled});
            return flag ? ${resultClass }.${successMethod}(Boolean.TRUE):${resultClass }.${errorMethod}("操作数据失败，请稍后再试");
        }
    </#if>

    private ${entityName} convert(${queryDTO} source) {
       return java.util.Optional.ofNullable(source).map(sc->{
                ${entityName} target = new ${entityName}();
                BeanUtils.copyProperties(sc, target);
                return target;
       }).orElse(null);
    }

    private ${entityName} convert(${updateDTO} source) {
         return java.util.Optional.ofNullable(source).map(sc->{
             ${entityName} target = new ${entityName}();
             BeanUtils.copyProperties(sc, target);
             return target;
         }).orElse(null);
    }

     <#if "${statucFlag}" =="1">
             private ${entityName} convert(${updateStatusDTO} source) {
                 return java.util.Optional.ofNullable(source).map(sc->{
                    ${entityName} target = new ${entityName}();
                    BeanUtils.copyProperties(sc, target);
                    return target;
                 }).orElse(null);
             }
     </#if>

       private ${entityName} convert(${addDTO} source) {
          return java.util.Optional.ofNullable(source).map(sc->{
             ${entityName} target = new ${entityName}();
             BeanUtils.copyProperties(sc, target);
             return target;
          }).orElse(null);
       }

     private ${voName} convert(${entityName} source) {
       return java.util.Optional.ofNullable(source).map(sc->{
          ${voName} target = new ${voName}();
          BeanUtils.copyProperties(source, target);
          return target;
       }).orElse(null);
     }

     private List<${voName}> convert(List<${entityName}> sources) {
        return java.util.Optional.ofNullable(sources).map(scs->{
          return scs.stream().map(source->{
            return convert(source);
          }).collect(java.util.stream.Collectors.toList());
        }).orElse(null);
     }

      private IPage<${voName}> convert(IPage<${entityName}> sources) {
             return java.util.Optional.ofNullable(sources).map(scs->{
                  IPage<${voName}> target = new com.baomidou.mybatisplus.extension.plugins.pagination.Page();
                  BeanUtils.copyProperties(scs,target);
                  List<${voName}> voNames = convert(scs.getRecords());
                  target.setRecords(voNames);

                 return target;
             }).orElse(null);
      }
}